package Inet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
//在这个代码里无法实现多个客户端访问
//而且 clientSocket也没有关闭
public class TcpEchoServer {
    //ServerSocket  是服务器端用的
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");


        while (true) {
            //Socket 用于收接信息
            Socket clientSocket = serverSocket.accept();
            processConnection(clientSocket);

        }
    }

    //通过这个方法来处理一个连接
    private void processConnection(Socket clientSocket) throws IOException {
        //1、打印一个日志 说明客户端上线了
        System.out.printf("[%s,%d] 客户端上线\n", clientSocket.getInetAddress(),clientSocket.getPort());

        //2、从socket 中获取到流对象，来进行进一步的后续操作
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()){
            //3、也搞一个循环 因为针对一个连接 也可能会有多个请求
            Scanner scanner = new Scanner(inputStream);
            while (true) {
                //3.1 读取请求并解析
                if (!scanner.hasNext()) {
                    System.out.printf("[%s,%d] 客户端上线\n", clientSocket.getInetAddress(),clientSocket.getPort());
                }
                String request = scanner.next();

                //3.2根据请求计算响应
                String response = process(request);
                //3.3 把响应写回客户端
                outputStream.write(response.getBytes());
                //3.4 打印日志
                System.out.printf("[%s:%d] req=%s, resp=%s\n",clientSocket.getInetAddress(),clientSocket.getPort(),request,response);

            }
        } finally {
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request + "\n";
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
